﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using mmCore.Classes;
using mmCore.Common;
using mmCore.Interfaces;

namespace mmXmlDataProvider
{
    public class XmlDataProvider : IDataProvider
    {
        #region CONST

        public const string ProviderVersion = "0.1.0.0";

        #endregion CONST

        #region PRIVATE

        [Serializable]
        public class MovieList
        {
            public List<Movie> Movies { set; get; }
            public string Version { set; get; }
        }

        #endregion PRIVATE

        #region METHODS

        public List<Movie> ReadMovies(string aPath)
        {
            if (!File.Exists(aPath))
            {
                return new List<Movie>();
            }

            var fs = new FileStream(aPath, FileMode.Open);
            var movies = ReadMovies(fs);
            fs.Close();
            return movies;
        }

        public List<Movie> ReadMovies(Stream str)
        {
            MovieList listMovies;

            try
            {
                var xmlSerializer = new XmlSerializer(typeof(MovieList));
                TextReader trReader = new StreamReader(str);
                listMovies = (MovieList)xmlSerializer.Deserialize(trReader);
            }
            catch
            {
                return null;
            }

            return listMovies.Movies;
        }

        public bool SaveMovies(string aPath, List<Movie> aMovies)
        {
            var fs = new FileStream(aPath, FileMode.Create);
            bool result = SaveMovies(fs, aMovies);
            fs.Close();
            return result;
        }

        public bool SaveMovies(Stream str, List<Movie> aMovies)
        {
            try
            {
                var lstProduct = new MovieList { Movies = aMovies, Version = ProviderVersion };
                var xmlSerializer = new XmlSerializer(typeof(MovieList));
                TextWriter twWriter = new StreamWriter(str);
                xmlSerializer.Serialize(twWriter, lstProduct);
            }
            catch(Exception ex)
            {
                ExceptionManager.ReportError(ex);
                return false;
            }

            return true;
        }

        #endregion METHODS
    }
}
